package main

import (
	"fmt"
	"os"
	"os/signal"
	"syscall"

	_ "qkstatis/db"
	_ "qkstatis/routers"
	_ "qkstatis/statis"

	_ "doubimeizhi.com/config/xml"
	"doubimeizhi.com/utility"

	"github.com/astaxie/beego"
	log "github.com/cihub/seelog"
)

func main() {
	if !utility.CheckAndRecordPid("qkstatis_server.pid") {
		fmt.Println("process already exists, so quit")
		return
	}
	logger, err := log.LoggerFromConfigAsFile("conf/seelog.xml")
	if err != nil {
		panic(err)
		return
	}
	log.ReplaceLogger(logger)
	defer logger.Flush()

	go handleSignals()

	beego.Run()
}

func handleSignals() {
	sigChan := make(chan os.Signal)
	signal.Notify(
		sigChan,
		syscall.SIGHUP,
	)

	<-sigChan

	pid := syscall.Getpid()
	log.Errorf("pid: %d, Received SIGHUP.", pid)

	log.Error("Server quit!")
	log.Current.Flush()

	if process, err := os.FindProcess(pid); err == nil {
		process.Kill()
	}
}
